1 using System;
2 using UnityEngine;
3
4 namespace UnityStandardAssets.Cameras
5 {
6 public abstract class AbstractTargetFollower : MonoBehaviour
7 {
8 public enum UpdateType // The available methods of updating are:
9 {
10 FixedUpdate, // Update in FixedUpdate (for tracking rigidbodies).
11 LateUpdate, // Update in LateUpdate. (for tracking objects that are moved in Update)
12 ManualUpdate, // user must call to update camera
13 }
14
15 [SerializeField] protected Transform m_Target; // The target object to follow
16 [SerializeField] private bool m_AutoTargetPlayer = true; // Whether the rig should automatically target the player.
17 [SerializeField] private UpdateType m_UpdateType; // stores the selected update type
18
19 protected Rigidbody targetRigidbody;
20
21
22 protected virtual void Start()
23 {
24 // if auto targeting is used, find the object tagged "Player"
25 // any class inheriting from this should call base.Start() to perform this action!
26 if (m_AutoTargetPlayer)
27 {
28 FindAndTargetPlayer();
29 }
30 if (m_Target == null) return;
31 targetRigidbody = m_Target.GetComponent<Rigidbody>();
32 }
33
34
35 private void FixedUpdate()
36 {
37 // we update from here if updatetype is set to Fixed, or in auto mode,
38 // if the target has a rigidbody, and isn't kinematic.
39 if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf))
40 {
41 FindAndTargetPlayer();
42 }
43 if (m_UpdateType == UpdateType.FixedUpdate)
44 {
45 FollowTarget(Time.deltaTime);
46 }
47 }
48
49
50 private void LateUpdate()
51 {
52 // we update from here if updatetype is set to Late, or in auto mode,
53 // if the target does not have a rigidbody, or - does have a rigidbody but is set to kinematic.
54 if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf))
55 {
56 FindAndTargetPlayer();
57 }
58 if (m_UpdateType == UpdateType.LateUpdate)
59 {
60 FollowTarget(Time.deltaTime);
61 }
62 }
63
64
65 public void ManualUpdate()
66 {
67 // we update from here if updatetype is set to Late, or in auto mode,
68 // if the target does not have a rigidbody, or - does have a rigidbody but is set to kinematic.
69 if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf))
70 {
71 FindAndTargetPlayer();
72 }
73 if (m_UpdateType == UpdateType.ManualUpdate)
74 {
75 FollowTarget(Time.deltaTime);
76 }
77 }
78
79 protected abstract void FollowTarget(float deltaTime);
80
81
82 public void FindAndTargetPlayer()
83 {
84 // auto target an object tagged player, if no target has been assigned
85 var targetObj = GameObject.FindGameObjectWithTag("Player");
86 if (targetObj)
87 {
88 SetTarget(targetObj.transform);
89 }
90 }
91
92
93 public virtual void SetTarget(Transform newTransform)
94 {
95 m_Target = newTransform;
96 }
97
98
99 public Transform Target
100 {
101 get { return m_Target; }
102 }
103 }
104 }